<template>
  <view class="step-1">
    <!--每日练习 步骤1-->
    <u--form labelPosition="left" :required="true" :model="jsonData" :rules="rules" ref="uForm">
      <view class="line" style="height: 10px"></view>
      <view class="item-info">
        <u-form-item :label="practiceNameLabel" prop="practiceName" labelPosition="top" required>
          <u--textarea v-model="jsonData.practiceName" border="none"
            :placeholder="'请输入' + practiceNameLabel"></u--textarea>
        </u-form-item>
        <u-form-item label="备注说明" prop="remark" labelPosition="top" class="top-layout">
          <u--textarea v-model="jsonData.remark" border="none" placeholder="请输入说明"></u--textarea>
        </u-form-item>
        <view class="line" style="height: 3px"></view>
        <u-form-item label="及格分数" prop="passScore" borderBottom required>
          <view class="flex flex-row flex-end item-center score">
            <u--input v-model="jsonData.passScore" border="none" type="number" />
            <view>分</view>
          </view>
        </u-form-item>
        <u-form-item label="开始时间" prop="startTime" borderBottom required @click="startTimeShow = true; hideKeyboard()"
          ref="item1">
          <u--input v-model="jsonData.startTime" disabled disabledColor="#ffffff" placeholder="请选择"
            border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="结束时间" prop="endTime" borderBottom required @click="endTimeShow = true; hideKeyboard()"
          ref="item1">
          <u--input v-model="jsonData.endTime" disabled disabledColor="#ffffff" placeholder="请选择"
            border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item :label="timeLabel" prop="time">
          <view class="flex flex-row flex-end item-center score">
            <u--input v-model="jsonData.time" border="none" />
            <view>分钟</view>
          </view>
        </u-form-item>
        <view class="line" style="height: 3px"></view>

        <u-form-item v-if="practiceType == '4'" label="奖品配置" prop="awardSetting" required @click="awardSettingOpen">
          <text class="awardSetting" :class="jsonData.awardSetting ? 'awardSetting-active' : ''">{{ jsonData.awardSetting ? '已设置' : '请设置' }}</text>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="登录配置" prop="loginSetLabel" required @click="loginSetShow = true; hideKeyboard()" ref="item1"
          :borderBottom="jsonData.loginSet === 1">
          <u--input v-model="jsonData.loginSetLabel" disabled disabledColor="#ffffff" placeholder="请选择"
            border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="密钥" required v-if="jsonData.loginSet === 1">
          <view class="flex flex-row flex-end item-center ">
            <u--input v-model="jsonData.loginKey" border="none" placeholder="请输入密钥" />
          </view>
        </u-form-item>

      </view>
      <view class="line" style="height: 10px"></view>
      <view class="item-info">
        <view class="item-title">登录信息配置</view>
        <view class="line" style="height: 3px"></view>
        <view v-for="(item, index) in jsonData.information" :key="index">
          <u-form-item :label="item.label" borderBottom :required="item.required" @click="loginConfigOpen(item)">
            <view class="flex flex-row flex-end item-center">
              <view class="f_1"></view>
              <view>
                <image src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/improve/edit.svg"
                  class="edit-img" />
              </view>
            </view>
          </u-form-item>
        </view>
      </view>
    </u--form>

    <view class="add-loginConfig modal flex-row  center" @click="addLoginConfigShow">
      <u-icon name="plus-circle" color="#37B874" size="20"></u-icon>
      <view style="margin-left: 12px" class="btn-txt">新增信息填写项</view>
    </view>
    <view class="btn-item">
      <view class="btn" @click="submit">{{ jsonData.uuid ? '确定' : '下一步' }}</view>
    </view>


    <!--开始时间-->
    <u-datetime-picker mode="datetime" :formatter="formatter" :show="startTimeShow" :value="startDatetime"
      closeOnClickOverlay @confirm="handleConfirm($event, 'start')" @cancel="handleClose('start')"
      @close="handleClose('start')" ref="datetimePicker"></u-datetime-picker>
    <!--结束时间-->
    <u-datetime-picker mode="datetime" :formatter="formatter" :show="endTimeShow" :value="endDatetime"
      closeOnClickOverlay @confirm="handleConfirm($event, 'end')" @cancel="handleClose('end')"
      @close="handleClose('end')" ref="datetimePicker"></u-datetime-picker>

    <u-action-sheet :show="loginSetShow" :actions="loginType" title="登录配置" @close="loginSetClose"
      @select="loginSetSelect">
    </u-action-sheet>
    <LoginConfigPopup ref="LoginConfigPopup" @edit="edit" @remove="remove" @moveUp="moveUp" @moveDown="moveDown"
      @switchChange="switchChange"></LoginConfigPopup>
    <AddLoginConfigPopup ref="AddLoginConfigPopup" @addInformation="addInformation"></AddLoginConfigPopup>
    <AwardSetting ref="awardSettingRef" @confirm="awardConfirm"></AwardSetting>
  </view>
</template>
<script>
import { loginType } from "@/improve/components/enum";
import LoginConfigPopup from "./LoginConfigPopup.vue";
import AddLoginConfigPopup from "./AddLoginConfigPopup.vue";
import AwardSetting from "./AwardSetting.vue";

export default {
  name: "Step1",
  components: { AddLoginConfigPopup, LoginConfigPopup, AwardSetting },
  inject: ['prop_practice', "pro_practiceType"],
  data() {
    return {
      startTimeShow: false,
      endTimeShow: false,
      loginSetShow: false,
      loginType,
      startDatetime: Number(new Date()),
      endDatetime: Number(new Date()),
      jsonData: {
        uuid: null,
        awardSetting: false, // 是否设置奖品
        practiceName: "",
        remark: "",//备注
        passScore: '',//及格分数
        startTime: "",
        endTime: null,
        time: null,
        loginSet: "",
        loginSetLabel: "",
        loginKey: "",
        awardTime: "",
        awardLinkWay: "",
        awardList: null,
        information: [
          {
            label: "考生姓名",
            value: "",
            disable: true,
            required: true,
            desc: "请输入真实姓名",
            type: "1",
            multi: "1",
            options: [""]
          },
          {
            label: "手机号码",
            value: "",
            disable: true,
            required: true,
            desc: "请输入手机号码",
            type: "1",
            multi: "1",
            options: [""]
          }
        ]
      },
      rules: {
        practiceName: [
          {
            required: true,
            message: '请输入练习名称',
            trigger: ['change', 'blur'],
          },
          {
            min: 1,
            max: 45,
            message: '长度在1-45个字符之间'
          },
        ],
        remark: [
          {
            min: 1,
            max: 200,
            message: '长度在1-200个字符之间'
          },
        ],
        passScore: [
          {
            required: true,
            message: '请输入及格分数',
            trigger: ['change'],
          },
        ],
        startTime: {
          type: 'string',
          required: true,
          message: '请选择开始时间',
          trigger: ['change']
        },
        endTime: {
          type: 'string',
          required: true,
          message: '请选择结束时间',
          trigger: ['change']
        },
        loginSetLabel: {
          type: 'string',
          required: true,
          message: '请选择登录配置',
          trigger: ['blur', 'change']
        },
      }
    }
  },
  computed: {
    practiceType() {
      return this.pro_practiceType()
    },
    practiceNameLabel() {
      if (this.pro_practiceType() === "3") {
        return "竞赛名称"
      }
      if (this.pro_practiceType() === "4") {
        return "答题名称"
      }
      return "练习名称"
    },
    timeLabel() {
      if (this.pro_practiceType() === "3") {
        return "竞赛时长"
      }
      if (this.pro_practiceType() === "4") {
        return "答题时长"
      }
      return "练习时长"
    }
  },
  methods: {
    awardConfirm(data) {
      this.jsonData.awardSetting = true,
        this.jsonData = { ...this.jsonData, ...data }
    },
    awardSettingOpen() {
      const detail = this.prop_practice()
      const data = detail ? {
        awardTime: detail.awardTime,
        awardLinkWay: detail.awardLinkWay,
        awardList: detail.awardList
      } : undefined
      this.$refs.awardSettingRef.open(data)
      this.hideKeyboard()
    },
    // 格式月份
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      return value
    },
    handleConfirm(e, type) {
      if (type === 'end') {
        this.endTimeShow = false;
        this.jsonData.endTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
        this.$refs.uForm.validateField('endTime')
      } else {
        this.startTimeShow = false;
        this.jsonData.startTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
        this.$refs.uForm.validateField('startTime')
      }
    },
    handleClose(type) {
      if (type === 'end') {
        this.endTimeShow = false;
        this.$refs.uForm.validateField('endTime')
      } else {
        this.startTimeShow = false;
        this.$refs.uForm.validateField('startTime')
      }
    },
    loginSetSelect(item) {
      this.jsonData.loginSet = item.value
      this.jsonData.loginSetLabel = item.name

    },
    loginSetClose() {
      this.loginSetShow = false;
      this.$refs.uForm.validateField('loginSetLabel')
    },
    hideKeyboard() {
      uni.hideKeyboard()
    },
    //添加配置项
    addLoginConfigShow() {
      this.$refs.AddLoginConfigPopup.open(null);
    },
    addInformation({ data, isAdd }) {
      const index = isAdd ? this.jsonData.information.length : this.getIndexByLabel(data.oldLabel)
      this.$set(this.jsonData.information, index, data); //
    },
    //编辑登录配置项
    loginConfigOpen(item) {
      this.$refs.LoginConfigPopup.open(item)
    },
    getIndexByLabel(label) {
      return this.jsonData.information.findIndex(item => item.label === label)
    },
    switchChange({ label, switchFl }) {
      const index = this.getIndexByLabel(label)
      this.jsonData.information[index].required = switchFl
    },
    edit(label) {
      const index = this.getIndexByLabel(label)
      this.$refs.AddLoginConfigPopup.open(this.jsonData.information[index])
    },
    //删除配置登录信息
    remove(label) {
      this.jsonData.information.splice(this.getIndexByLabel(label), 1);
    },
    // 上移一位
    moveUp(label) {
      const index = this.getIndexByLabel(label)
      if (index > 0 && index < this.jsonData.information.length) {
        const data = JSON.parse(JSON.stringify(this.jsonData.information[index]));
        const nextData = JSON.parse(JSON.stringify(this.jsonData.information[index - 1]));

        this.$set(this.jsonData.information, index - 1, data); //
        this.$set(this.jsonData.information, index, nextData); // 使用 Vue.set
      }
    },
    //下移一位
    moveDown(label) {
      const index = this.getIndexByLabel(label)
      if (index >= 0 && index < this.jsonData.information.length - 1) {
        const data = JSON.parse(JSON.stringify(this.jsonData.information[index]));
        const nextData = JSON.parse(JSON.stringify(this.jsonData.information[index + 1]));
        this.$set(this.jsonData.information, index + 1, data);
        this.$set(this.jsonData.information, index, nextData);
      }
    },
    async submit() {
      // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
      const data = await this.$refs.uForm.validate().then(res => {
        if (this.practiceType == '4' && !this.jsonData.awardSetting) {
          this.showToast("请设置奖品")
          return;
        }
        if (this.jsonData.loginSet === 1 && !this.jsonData.loginKey) {
          this.showToast("请输入密钥")
          return;
        }
        this.$emit("updatePostParams", { ...this.prop_practice(), ...this.jsonData }, 2)
        return true;
      }).catch(errors => {
        if (errors[0].field === "practiceName") {
          this.showToast("请输入" + this.practiceNameLabel)
          return
        }
        this.showToast(errors[0].message)
      })
      return data
    }
    ,
    showToast(msg) {
      uni.showToast({
        title: msg,
        icon: "none",
        duration: 2000
      });
    },
    //修改进入 初始数据
    initJsonData() {
      if (this.prop_practice()) {
        //进入修改界面
        const data = JSON.parse(JSON.stringify(this.prop_practice()));
        for (let key in data) {
          switch (key) {
            case 'informationJson':
              this.jsonData[key] = JSON.parse(data[key]);
              break;
            case 'loginSet':
              this.jsonData.loginSetLabel = this.loginType.find((item) => item.value === data[key]).name;
              this.jsonData[key] = data[key];
              break;
            case 'startTime':
            case 'endTime':
              this.jsonData[key] = data[key];
              this[key === 'startTime' ? 'startDatetime' : 'endDatetime'] = new Date(data[key]).getTime();
              break;
            default:
              this.jsonData[key] = data[key];
          }
        }
        this.jsonData.passScore = data.passScore.toString()
        this.jsonData.awardSetting = data.awardList && data.awardList.length != 0
      }
    }
  },
  created() {
    this.initJsonData()
  }
  ,
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules)
    this.$refs.datetimePicker.setFormatter(this.formatter)
  }
  ,
}
</script>
<style scoped lang="scss">
.awardSetting {
  text-align: right;
  font-size: 32rpx;
  color: #c0c4cc;
  padding-right: 36rpx;

  &-active {
    color: #37B874;
  }
}

.step-1 {
  .item-title {
    font-weight: bold;
    color: #333333;
    font-size: 32rpx;
    padding-left: 21px;
    height: 60px;
    line-height: 60px;
  }

  .item-info {
    border-radius: 12px;
    background-color: #FFFFFF;

    .edit-img {
      width: 24px;
      height: 24px
    }
  }

  .add-loginConfig {
    height: 55px;
    background-color: #FFFFFF;

    .btn-txt {
      color: #37B874;
      font-size: 28rpx;
    }
  }
}
</style>